package com.itheima.reggie.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据:{}",orders);
        ordersService.submit(orders);
        return R.success("下单成功!");
    }

    /**
     * 查询订单详情，分页展示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Transactional
    @GetMapping("/userPage")
    public R<Page> getOrderWithDetail(int page, int pageSize) {
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        Page<OrdersDto> ordersDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //进行分页查询
        ordersService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");

        //获取原页面数据
        List<Orders> records=pageInfo.getRecords();

        //原数据缺少订单数量，进行更改
        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(item, ordersDto);
            Long Id = item.getId();
            //根据id查分类对象
            Orders orders = ordersService.getById(Id);
            String number = orders.getNumber();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,number);
            List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);
            //初始化订单数
            int num=0;
            //从订单详情表OrderDetail获取number
            for(OrderDetail detail:orderDetailList){
                num+=detail.getNumber().intValue();
            }
            ordersDto.setSumNum(num);
            return ordersDto;
        }).collect(Collectors.toList());
        //将修改之后的页面数据赋值
        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }

    /**
     * 再来一单
     * @param order
     * @return
     */
    @PostMapping("/again")
    public R<String>again(@RequestBody Orders order){
        log.info("再来一单");
        //更新订单表 根据id
        Long id = order.getId();
        Orders orders = ordersService.getById(id);
        long orderId = IdWorker.getId();//MP自动生成id订单号
        //设置属性
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        //将生成的订单表提交
        ordersService.save(orders);
        //更新订单详情表
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,id);

        List<OrderDetail> list = orderDetailService.list(lqw);
        list.stream().map((item) -> {
            //MP生成
            long detailId = IdWorker.getId();
            //设置订单表id
            item.setOrderId(orderId);
            //设置订单详情表id
            item.setId(detailId);
            return item;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(list);
        return R.success("再来一单成功!");
    }

    /**
     * 展示后端订单详情
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String number, String beginTime,String endTime){
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //1.根据订单号模糊查询
        lqw.like(!StringUtils.isEmpty(number),Orders::getNumber,number);

        //2. 根据DateTime 范围查询
        if (beginTime !=null &&endTime != null){
            lqw.eq(Orders::getOrderTime,beginTime);
            lqw.eq(Orders::getOrderTime,endTime);
        }
        //根据订单创建时间降序排列
        lqw.orderByDesc(Orders::getOrderTime);

        ordersService.page(pageInfo,lqw);

        //由于没有获取到用户名称 进行设置用户名称
        List<Orders> records = pageInfo.getRecords();
        records.stream().map((item) -> {
            item.setUserName("客户:"+item.getUserId());
            return item;
        }).collect(Collectors.toList());

        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> setStatus(@RequestBody Orders orders){
        //获取订单id
        Long ordersId = orders.getId();
        //获取订单状态
        Integer status = orders.getStatus();
        Orders order = ordersService.getById(ordersId);
        order.setStatus(status);
        ordersService.updateById(order);
        return R.success("派送成功!");
    }
}
